package com.futureCloudMOM.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.futureCloudMOM.common.exception.base.BaseException;
import com.futureCloudMOM.common.utils.bean.BeanUtils;
import com.futureCloudMOM.core.base.service.impl.BaseServiceImpl;
import com.futureCloudMOM.core.domain.*;
import com.futureCloudMOM.core.mapper.*;
import com.futureCloudMOM.core.service.WmsBarCodeInfoService;
import com.futureCloudMOM.core.service.WmsBarCodeQuanService;
import com.futureCloudMOM.core.service.WmsBarCodeTransferService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【WMS_BarCodeInfo】的数据库操作Service实现
 *
 * @author Administrator
 * @since 2023-06-07 09:14:43
 */
@AllArgsConstructor
@Service
public class WmsBarCodeInfoServiceImpl extends BaseServiceImpl<WmsBarCodeInfoMapper, WmsBarCodeInfo> implements WmsBarCodeInfoService {

    private final WmsBarCodeInfoMapper barCodeInfoMapper;
    // 条码库位
    private final WmsBarCodeQuanService wmsBarCodeQuanService;
    // 条码事务
    private final WmsBarCodeTransferService wmsBarCodeTransferService;
    // 业务订单子表
    private final WmsInvoiceSubMapper wmsInvoiceSubMapper;
    // 备货表
    private final WmsBarcodeinfoSparesMapper wmsBarcodeinfoSparesMapper;


    @Override
    public void delByState(Long InvoiceMainId, Long InvoiceSubId) {
        List<WmsBarCodeInfo> list = barCodeInfoMapper.selectList(new LambdaQueryWrapper<WmsBarCodeInfo>()
                .eq(WmsBarCodeInfo::getBillID, InvoiceMainId)
                .eq(WmsBarCodeInfo::getBillSubID, InvoiceSubId)
                .eq(WmsBarCodeInfo::getStatus, -1));
        list.forEach(item -> {
            //删除条码默认库存位
            wmsBarCodeQuanService.delBarcodeQuanByCode(item.getBarCode());
            //删除条码生成事务
            wmsBarCodeTransferService.delBarCodeTransferByCode(item.getBarCode());
            barCodeInfoMapper.deleteById(item.getId());
        });
    }

    @Override
    public List<WmsBarCodeInfo> CreateBarCode(Long InvoiceMainId) {

        //调用存储过程创建条码
        barCodeInfoMapper.callProcBarCode(InvoiceMainId);
        //得到创建的条码
        /*List<WmsInvoiceSub> wmsSubList = wmsInvoiceSubMapper.selectList(new LambdaQueryWrapper<WmsInvoiceSub>()
                .eq(WmsInvoiceSub::getMainId,InvoiceMainId));*/
        //调用proc生成并返回条码
        /* wmsSubList.forEach(sub -> {
         *//**
         * 判断条码张数 得到流水位
         *//*
            BasicMaterial material = basicMaterialMapper.selectById(sub.getMaterialId());
            //订单数大于物料最小包装数量
            if (sub.getQty().compareTo(material.getMinPackage())==1){
            int codeNumber=sub.getQty().divide(material.getMinPackage(),0, RoundingMode.CEILING).intValue();
            //计算是否有尾箱条码
            int codeNumberRemain =sub.getQty().remainder(material.getMinPackage()).intValue()>0  ?  1 : 0;
            //所有条码张数
            int codeNumAll=codeNumber+codeNumberRemain;

            }
        });*/
        return barCodeInfoMapper.selectList(new LambdaQueryWrapper<WmsBarCodeInfo>()
                .eq(WmsBarCodeInfo::getBillID, InvoiceMainId));
    }

    @Override
    public void DelBarCode(Long InvoiceMainId) {
        List<WmsBarCodeInfo> list = barCodeInfoMapper.selectList(new LambdaQueryWrapper<WmsBarCodeInfo>()
                .eq(WmsBarCodeInfo::getBillID, InvoiceMainId));
        list.forEach(item -> {
            //删除条码默认库存位
            wmsBarCodeQuanService.delBarcodeQuanByCode(item.getBarCode());
            //删除条码生成事务
            wmsBarCodeTransferService.delBarCodeTransferByCode(item.getBarCode());
            barCodeInfoMapper.deleteById(item.getId());
        });
    }

    @Override
    @Transactional
    public void stockMarkerByInvoiceSub(List<WmsInvoiceSub> wmsInvoiceSubs, Long billTypeId) {

        wmsInvoiceSubs.forEach(sub -> {
            //2.按订单仓库找到非锁定可用库存
            // 根据仓库ID 物料ID 查询条码库位信息
            List<WmsBarCodeQuan> quanList = wmsBarCodeQuanService.list(new LambdaQueryWrapper<WmsBarCodeQuan>()
                    .eq(WmsBarCodeQuan::getWHID, sub.getWHID())
                    .eq(WmsBarCodeQuan::getMaterialID, sub.getMaterialId())
                    .eq(WmsBarCodeQuan::getDeleted, 0));
            // 抽出条码号
            List<String> strings = quanList.stream().map(WmsBarCodeQuan::getBarCode).collect(Collectors.toList());
            // 根据条码号查询条码信息并按照批次号排序 状态是正常的条码
            List<WmsBarCodeInfo> codeInfoList = list(new LambdaQueryWrapper<WmsBarCodeInfo>()
                    .eq(WmsBarCodeInfo::getStatus, 0)
                    .in(WmsBarCodeInfo::getBarCode, strings)
                    .orderByAsc(WmsBarCodeInfo::getBatchNum));
            if (ObjectUtils.isEmpty(codeInfoList)) {
                // 没有可用的条码 该子表数据的备货标识改成备货失败无库存
                sub.setStockMarker(1);
            } else {
                // 数量满足要领出的数量后 领出的条码进行备货锁定
                // 条码数量叠加
                BigDecimal qty = BigDecimal.ZERO;
                // 要更新的条码
                List<WmsBarCodeInfo> codeInfos = new ArrayList<>();
                for (WmsBarCodeInfo wmsBarCodeInfo : codeInfoList) {
                    qty = qty.add(wmsBarCodeInfo.getQuantity());
                    // 判断数量是否 >= 要领取的数量
                    if (qty.compareTo(sub.getQty()) >= 0) {
                        codeInfos.add(wmsBarCodeInfo);
                        // 备货标识为 备货成功
                        sub.setStockMarker(0);
                        return;
                    } else {
                        codeInfos.add(wmsBarCodeInfo);
                    }
                }
                // 可用库存不满足数量
                if (sub.getQty().compareTo(qty) > 0) {
                    // 根据余量生成新的子表数据
                    WmsInvoiceSub wmsInvoiceSub = new WmsInvoiceSub();
                    // 数据复制
                    BeanUtils.copyBeanProp(sub, wmsInvoiceSub);
                    wmsInvoiceSub.setQty(sub.getQty().subtract(qty));
                    wmsInvoiceSub.setStockMarker(1);
                    wmsInvoiceSubMapper.insert(wmsInvoiceSub);
                    // 老数据的数量更改为可备货的数量 备货标识为 备货成功
                    sub.setStockMarker(0);
                    sub.setQty(qty);
                }
                // 更新条码状态为 备货锁定
                codeInfos.forEach(item -> {
                    item.setStatus(1L);
                    updateById(item);
                    // 备货的条码放进备货表
                    WmsBarcodeinfoSpares spares = new WmsBarcodeinfoSpares();
                    spares.setBilltype(billTypeId);
                    spares.setMainid(sub.getMainId());
                    spares.setSubid(sub.getId());
                    spares.setBarcode(item.getBarCode());
                    spares.setMaterialid(item.getMaterialID());
                    spares.setQuantity(item.getQuantity());
                    // 备货表状态
                    spares.setStatus(0);
                    wmsBarcodeinfoSparesMapper.insert(spares);
                });
            }
            // 子表数据更新
            wmsInvoiceSubMapper.updateById(sub);
        });
    }

}
